package com.acme.bankapp.service.bank;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.bankapp.domain.bank.client.Client;
import com.acme.bankapp.service.bank.exception.ClientExistsException;

public class BankService {
	public static void addClient(Bank bank, Client client) throws ArrayIndexOutOfBoundsException, ClientExistsException {
		bank.addClient(client);
		
		saveBank(bank);
	}

	public static void printBalance(Bank bank) {
		System.out.println("Balance:");
		for (int i = 0; i < bank.getCountClients(); i++) {
			Client client = bank.getClients()[i];
			System.out.println("Client[" + (i+1) + "]: " + client);
		}
	}
	
	public static void printMaximumAmountToWithdraw(Bank bank) {
		System.out.println("Maximum amount to withdraw:");
		for (int i = 0; i < bank.getCountClients(); i++) {
			Client client = bank.getClients()[i];
			System.out.println("Client[" + (i+1) + "]: " + client);
		}
	}
	
	public static final String FILE_NAME_FOR_SERIALIZATION = "d:\\temp\\ser_feed.dat";
	
	public static void saveBank(Bank bank) {
		ObjectOutputStream stream = null;
		FileOutputStream file = null;
		try {
			file = new FileOutputStream(FILE_NAME_FOR_SERIALIZATION);
			stream = new ObjectOutputStream(file);
			stream.writeObject(bank);
		} catch (FileNotFoundException exception) {
			System.out.println("File for serialization not found");
		} catch (NotSerializableException exception) {
			System.out.println("Not serializable class");
		} catch (IOException exception) {
			System.out.println("Error IO file for serialization");
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (IOException e) { }
			}
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) { }
			}
		}
	}
	
	public static Bank readBank() {
		Bank bank = null;
		
		ObjectInputStream stream = null;
		FileInputStream file = null;
		try {
			file = new FileInputStream(FILE_NAME_FOR_SERIALIZATION);
			stream = new ObjectInputStream(file);
			bank = (Bank) stream.readObject();
		} catch (FileNotFoundException exception) {
			System.out.println("File for serialization not found");
		} catch (IOException exception) {
			System.out.println("Error IO file for serialization");
		} catch (ClassNotFoundException exception) {
			System.out.println("Some class not found");
		}
		finally {
			if (file != null) {
				try {
					file.close();
				} catch (IOException e) { }
			}
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) { }
			}
		}
		
		return bank;
	}
}
